package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.PlanRemind;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/5/4 10:25
 */
public class PlanRemindDetailFragment extends BaseFragment {
  protected static final String EXTRA_CONTENT =
      PlanRemindDetailActivity.class.getSimpleName() + "EXTRA_CONTENT";
  @BindView(R.id.tv_tipinfo) TextView tvTipinfo;
  @BindView(R.id.tv_deadtime) TextView tvDeadtime;
  @BindView(R.id.tv_remindTime) TextView tvRemindTime;
  @BindView(R.id.tv_remindperson) TextView tvRemindperson;
  @BindView(R.id.tv_remark) TextView tvRemark;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;
  private PlanRemind mContent;
  private final int REQUEST_CLOSE = 0;
  private final int REQUEST_DELAY = 1;
  private TextView tvDelaytime;
  private String postpone;
  private Dialog dialog;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mContent = (PlanRemind) getArguments().getSerializable(EXTRA_CONTENT);
    setTitleCustom(mContent.getTipinfo());
    postpone = "";//推迟时间
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_close_delay, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_close:
        //关闭
        showDialog(REQUEST_CLOSE);
        return true;
      case R.id.menu_item_delay:
        //推迟
        delayDialog();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void delayDialog() {
    View view =
        LayoutInflater.from(getActivity()).inflate(R.layout.dialog_delaytime_select, null, false);
    tvDelaytime = (TextView) view.findViewById(R.id.tv_delaytime);
    tvDelaytime.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(REQUEST_DELAY);
      }
    });
    dialog = new AlertDialog.Builder(getContext()).setTitle("推迟时间设置")
        .setView(view)
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialogInterface, int i) {
            if (TextUtils.isEmpty(postpone)) {
              ToastUtil.show("请选择推迟时间");
            } else {
              volleyPostDelay();
              dialog.dismiss();
            }
          }
        })
        .setNegativeButton("取消", null)
        .create();
    dialog.show();
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case REQUEST_CLOSE:
        //关闭
        dialog = BaseConfirmDialogFragment.newInstance("确定要关闭提醒吗？");
        break;
      case REQUEST_DELAY:
        //推迟时间
        dialog = new PlanDelayTimeDialogFragment();
        break;
      default:
        break;
    }

    FragmentManager fm = getFragmentManager();
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_plan_remind, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    tvTipinfo.setText(mContent.getTipinfo());
    tvDeadtime.setText(mContent.getOncedate());
    tvRemindTime.setText(mContent.getTiptimeStr());
    tvRemindperson.setText(mContent.getTipname());
    tvRemark.setText(mContent.getRemark());
    tvRegStaffName.setText(mContent.getRegStaffName());
    tvRegDate.setText(mContent.getRegDate());
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_CLOSE) {
      //关闭
      volleyPostClose();
    }
    if (requestCode == REQUEST_DELAY) {
      //推迟
      CustomerDialog delayTime =
          (CustomerDialog) data.getSerializableExtra(PlanDelayTimeDialogFragment.EXTRA_CONTENT);
      postpone = delayTime.getId();
      tvDelaytime.setText(delayTime.getName());
    }
  }

  private void volleyPostDelay() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_REMIND_DELAY);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mContent.getId());
    params.put("postpone", postpone);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private void volleyPostClose() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_REMIND_CLOSE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        } else {
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  public static PlanRemindDetailFragment newInstance(PlanRemind content) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    PlanRemindDetailFragment fragment = new PlanRemindDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
